using B.S.BaseData.Api.Read.Command.Hosp;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.AI;
using B.S.BataBase.Domain.DTO;
using B.S.BataBase.Domain.Hosp;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BaseData.Api.Read.CommandHandler.Hosp
{
    public class CarouselImageShowCommandHandler : IRequestHandler<CarouselImageShowCommand, APIResult<ApiPaging<CarouselImage>>>
    {
        private readonly IBaseRepository<CarouselImage> _repository;

        public CarouselImageShowCommandHandler(IBaseRepository<CarouselImage> repository)
        {
            _repository = repository;
        }

        public async Task<APIResult<ApiPaging<CarouselImage>>> Handle(CarouselImageShowCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<ApiPaging<CarouselImage>>();

            try
            {
                var query = _repository.GetAll().Where(x => !x.IsDeleted);

                // 关键词搜索
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(x => x.CarouselName.Contains(request.Keyword));
                }

                // 时间区间筛选
                if (request.StartTime != null && request.EndTime != null)
                {
                    query = query.Where(x => x.AddTime >= request.StartTime.Value && x.AddTime <= request.EndTime.Value);
                }
                else if (request.StartTime != null)
                {
                    query = query.Where(x => x.AddTime >= request.StartTime.Value);
                }
                else if (request.EndTime != null)
                {
                    query = query.Where(x => x.AddTime <= request.EndTime.Value);
                }
                var totaCount = query.Count();
                var pageCount = (int)Math.Ceiling(totaCount * 1.0 / request.pageSize);
                ApiPaging<CarouselImage> paging = new ApiPaging<CarouselImage>();
                paging.TotalPage = pageCount;
                paging.Total = totaCount;
                paging.PageData = query.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                result.Data = paging;
                result.Code = ApiEnum.Success;
                result.Msg = "轮播图加载成功";
                return result;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = $"加载轮播图失败：{ex.Message}";
                return await Task.FromResult(result);
            }
        }
    }
} 